﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using EngineOfEvermore.Common;
using AgateLib.Utility;
using AgateLib.WinForms;
using AgateLib.DisplayLib;

namespace EngineOfEvermore.Imaging.AgateImplementation
{
    class AgateImagePacker : IImagePacker
    {
        public IEnumerable<ImageMapFrame> PackFrames( Bitmap inputImage, 
            IEnumerable<Rectangle> frameAreas, Size? sizeHint )
        {
            var protoFrames = Util.Generate( () => new AgateImageMapFrameBuilder(), 
                frameAreas.Count() ).ToArray();

            _findTransparentAreas( inputImage, frameAreas.ToArray(), protoFrames );

            var atlasSize = _calculateSize( protoFrames, sizeHint );

            _convertAreas( protoFrames, atlasSize );

            var surface = _createSurface( protoFrames, inputImage, atlasSize );

            foreach ( var protoFrame in protoFrames )
            {
                protoFrame.Surface = surface;
            }

            return protoFrames.Select( proto => proto.Build() ).ToArray();
        }

        public Size CalculateSize( Bitmap bitmap, IFrameGenerator frameGenerator )
        {
            var frameAreas = frameGenerator.GenerateFrames( bitmap ).ToArray();
            var protoFrames = Util.Generate( () => new AgateImageMapFrameBuilder(), 
                frameAreas.Count() ).ToArray();

            _findTransparentAreas( bitmap, frameAreas, protoFrames );

            return Interop.Convert( _calculateSize( protoFrames, null ) );
        }

        private Surface _createSurface( AgateImageMapFrameBuilder[] protoFrames, Bitmap inputImage, 
            AgateLib.Geometry.Size atlasSize )
        {
            var pb = new PixelBuffer( Display.DefaultSurfaceFormat, atlasSize );

            foreach ( var frame in protoFrames )
            {
                _copyFrameToPixelBuffer( frame, pb, inputImage );
            }

            return new Surface( pb );
        }

        private void _copyFrameToPixelBuffer( AgateImageMapFrameBuilder frame, PixelBuffer pb, 
            Bitmap inputImage )
        {
            int width = frame.ConvertedArea.Width;
            int height = frame.ConvertedArea.Height;

            for ( int y = 0; y < height; ++y )
            {
                int srcY = frame.OriginalNonTransparentArea.Y + y;
                int destY = frame.ConvertedArea.Y + y;

                for ( int x = 0; x < width; ++x )
                {
                    int srcX = frame.OriginalNonTransparentArea.X + x;
                    int destX = frame.ConvertedArea.X + x;
                    var color = Interop.Convert( inputImage.GetPixel( srcX, srcY ) );
                    pb.SetPixel( destX, destY, color );
                }
            }
        }

        private void _convertAreas( AgateImageMapFrameBuilder[] protoFrames, 
            AgateLib.Geometry.Size atlasSize )
        {
            var rectPacker = new SurfacePacker.RectPacker<AgateImageMapFrameBuilder>( atlasSize );

            foreach ( var protoFrame in protoFrames )
            {
                if ( !protoFrame.IsEmpty )
                {
                    var size = Interop.Convert( protoFrame.OriginalNonTransparentArea.Size );
                    rectPacker.QueueObject( size, protoFrame );
                }
            }

            rectPacker.AddQueue();

            Debug.Assert( protoFrames.Where( f => !f.IsEmpty )
                .IsEquivalentTo( rectPacker.Select( h => h.Tag ) ) );

            foreach ( var packedRect in rectPacker )
            {
                var protoFrame = packedRect.Tag;
                protoFrame.ConvertedArea = Interop.Convert( packedRect.Rect );
            }
        }

        static void _findTransparentAreas( Bitmap sourceImage,
            Rectangle[] frameAreas, AgateImageMapFrameBuilder[] protoFrames )
        {
            Debug.Assert( frameAreas.Length == protoFrames.Length );

            // Calculate all non-transparent areas
            for ( int i = 0; i < frameAreas.Length; ++i )
            {
                var area = frameAreas[i];
                var frame = protoFrames[i];

                frame.OriginalArea = area;
                frame.OriginalNonTransparentArea = _getNonTransparentArea( sourceImage, area );

                frame.IsEmpty = frame.OriginalNonTransparentArea.IsEmpty;
            }
        }

        /// <summary>
        /// Finds the smallest rectangle in an area of the source image that contains all
        /// non-transparent pixels.
        /// </summary>
        static Rectangle _getNonTransparentArea( Bitmap src, Rectangle area )
        {
            Debug.Assert( new Rectangle( 0, 0, src.Width, src.Height ).Contains( area ) );

            int minX = int.MaxValue;
            int minY = int.MaxValue;
            int maxX = int.MinValue;
            int maxY = int.MinValue;

            for ( int y = area.Top; y < area.Bottom; ++y )
                for ( int x = area.Left; x < area.Right; ++x )
                {
                    Color color = src.GetPixel( x, y );

                    if ( color.A != 0 )
                    {
                        if ( x < minX )
                            minX = x;

                        if ( x > maxX )
                            maxX = x;

                        if ( y < minY )
                            minY = y;

                        if ( y > maxY )
                            maxY = y;
                    }
                }

            if ( minX > maxX )
            {
                return new Rectangle( 0, 0, 0, 0 );
            }
            else
            {
                return new Rectangle( minX, minY, maxX - minX + 1, maxY - minY + 1 );
            }
        }

        private static AgateLib.Geometry.Size _calculateSize( 
            IEnumerable<AgateImageMapFrameBuilder> protoFrames, Size? sizeHint )
        {
            if ( sizeHint.HasValue )
                return AgateLib.WinForms.Interop.Convert( sizeHint.Value );


            var nonEmptyFrames = protoFrames.Where( x => !x.IsEmpty ).ToArray();
            var atlasSize = new AgateLib.Geometry.Size( 32, 32 );
            bool incXInThisIteration = true;

            while ( true )
            {
                var rectPacker = 
                    new SurfacePacker.RectPacker<AgateImageMapFrameBuilder>( atlasSize );

                foreach ( var protoFrame in protoFrames )
                {
                    if ( !protoFrame.IsEmpty )
                    {
                        var size = Interop.Convert( protoFrame.OriginalNonTransparentArea.Size );
                        rectPacker.QueueObject( size, protoFrame );
                    }
                }

                rectPacker.AddQueue();

                var packed = rectPacker.Select( x => x.Tag ).ToArray();

                if ( packed.IsEquivalentTo( nonEmptyFrames ) )
                {
                    return atlasSize;
                }
                else
                {
                    if ( incXInThisIteration )
                    {
                        atlasSize.Width *= 2;
                    }
                    else
                    {
                        atlasSize.Height *= 2;
                    }

                    incXInThisIteration = !incXInThisIteration;

                    if ( atlasSize.Width > AgateLib.DisplayLib.Display.MaxSurfaceSize.Width ||
                         atlasSize.Height > AgateLib.DisplayLib.Display.MaxSurfaceSize.Height )
                    {
                        throw new ImageMapException( "Not all frames fit into one texture!" );
                    }
                }
            }
        }
    }
}
